{
  "nbformat": 4,
  "nbformat_minor": 0,
  "metadata": {
    "colab": {
      "provenance": []
    },
    "kernelspec": {
      "name": "python3",
      "display_name": "Python 3"
    },
    "language_info": {
      "name": "python"
    }
  },
  "cells": [
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "id": "3xW4O0zuKfWD"
      },
      "outputs": [],
      "source": [
        "import os\n",
        "from openai import OpenAI\n",
        "import json\n",
        "from google.colab import userdata"
      ]
    },
    {
      "cell_type": "code",
      "source": [
        "api_key = userdata.get('OPENAI_API_KEY')\n",
        "MODEL = \"gpt-4o-mini\"\n",
        "\n",
        "openai = OpenAI(api_key=api_key)"
      ],
      "metadata": {
        "id": "vUydnLeLKs03"
      },
      "execution_count": null,
      "outputs": []
    },
    {
      "cell_type": "markdown",
      "source": [
        "**Using system prompt to generate structured output**"
      ],
      "metadata": {
        "id": "blCx6gu1Vl46"
      }
    },
    {
      "cell_type": "markdown",
      "source": [
        "# Chat Completion API\n",
        "\n",
        "https://platform.openai.com/docs/guides/structured-outputs?api-mode=chat"
      ],
      "metadata": {
        "id": "5wlqKfVBKyjD"
      }
    },
    {
      "cell_type": "code",
      "source": [
        "system_prompt = \"\"\"\n",
        "Extract the event information from the users message and provide output in\n",
        "exact json format as follows -\n",
        "{'name': 'Dinner', 'date': 'Monday', 'participants': ['Michael', 'David']}\n",
        "\"\"\"\n",
        "response = openai.chat.completions.create(\n",
        "    model=MODEL,\n",
        "    messages=[\n",
        "        {\"role\": \"developer\", \"content\": system_prompt},\n",
        "        {\"role\": \"user\", \"content\": \"Alice and Bob are going to a science fair on Friday.\"},\n",
        "    ],\n",
        ")\n",
        "# Response is string not json\n",
        "print(response.choices[0].message.content)"
      ],
      "metadata": {
        "id": "dBrUkMCUKz0s",
        "colab": {
          "base_uri": "https://localhost:8080/"
        },
        "outputId": "e6adfc37-045a-4336-a92e-7c2606469cab"
      },
      "execution_count": null,
      "outputs": [
        {
          "output_type": "stream",
          "name": "stdout",
          "text": [
            "{'name': 'Science Fair', 'date': 'Friday', 'participants': ['Alice', 'Bob']}\n"
          ]
        }
      ]
    },
    {
      "cell_type": "markdown",
      "source": [
        "This will give ERROR because object properties in outupt are in single quotes"
      ],
      "metadata": {
        "id": "zbbl6F-1Sae2"
      }
    },
    {
      "cell_type": "code",
      "source": [
        "system_prompt = \"\"\"\n",
        "Extract the event information from the users message and provide output in\n",
        "exact json format as follows -\n",
        "{'name': 'Dinner', 'date': 'Monday', 'participants': ['Michael', 'David']}\n",
        "\"\"\"\n",
        "response = openai.chat.completions.create(\n",
        "    model=MODEL,\n",
        "    messages=[\n",
        "        {\"role\": \"developer\", \"content\": system_prompt},\n",
        "        {\"role\": \"user\", \"content\": \"Alice and Bob are going to a science fair on Friday.\"},\n",
        "    ],\n",
        ")\n",
        "print(response.choices[0].message.content)\n",
        "# This will give ERROR because object properties in outupt are in single quotes\n",
        "dictionary = json.loads(response.choices[0].message.content)\n",
        "print(dictionary)"
      ],
      "metadata": {
        "id": "WItchxDLK2x6"
      },
      "execution_count": null,
      "outputs": []
    },
    {
      "cell_type": "markdown",
      "source": [
        "After JSON parsing, you will receive a JSON key-value pair dictionary, not an object."
      ],
      "metadata": {
        "id": "D8rAuv08V4K0"
      }
    },
    {
      "cell_type": "code",
      "source": [
        "system_prompt = \"\"\"\n",
        "Extract the event information from the users message and provide output in\n",
        "exact json format as follows -\n",
        "{\"name\": \"Dinner\", \"date\": \"Monday\", \"participants\": [\"Michael\", \"David\"]}\n",
        "\"\"\"\n",
        "response = openai.chat.completions.create(\n",
        "    model=MODEL,\n",
        "    messages=[\n",
        "        {\"role\": \"developer\", \"content\": system_prompt},\n",
        "        {\"role\": \"user\", \"content\": \"Leonardo, Ivan and Alex will be joining Taylor for dinner on Tuesday night.\"},\n",
        "    ],\n",
        ")\n",
        "print(response.choices[0].message.content)\n",
        "dictionary = json.loads(response.choices[0].message.content) # Convert string to json\n",
        "print(dictionary)\n",
        "print(dictionary[\"name\"])\n",
        "# print(dictionary.name) # Will not work because dictionary is not an object"
      ],
      "metadata": {
        "colab": {
          "base_uri": "https://localhost:8080/"
        },
        "id": "BY42-QT9W_2D",
        "outputId": "f02659fd-ca33-4214-b26f-2847e35599dc"
      },
      "execution_count": null,
      "outputs": [
        {
          "output_type": "stream",
          "name": "stdout",
          "text": [
            "{\"name\": \"Dinner\", \"date\": \"Tuesday\", \"participants\": [\"Leonardo\", \"Ivan\", \"Alex\", \"Taylor\"]}\n",
            "{'name': 'Dinner', 'date': 'Tuesday', 'participants': ['Leonardo', 'Ivan', 'Alex', 'Taylor']}\n",
            "Dinner\n"
          ]
        }
      ]
    },
    {
      "cell_type": "markdown",
      "source": [
        "# Responses API\n",
        "\n",
        "https://platform.openai.com/docs/guides/structured-outputs?api-mode=responses"
      ],
      "metadata": {
        "id": "tCzSosP5K-JR"
      }
    },
    {
      "cell_type": "code",
      "source": [
        "system_prompt = \"\"\"\n",
        "Extract the event information from the users message and provide output in\n",
        "exact json format as follows -\n",
        "{\"name\": \"Dinner\", \"date\": \"Monday\", \"participants\": [\"Michael\", \"David\"]}\n",
        "\"\"\"\n",
        "response = openai.responses.create(\n",
        "    model=MODEL,\n",
        "    input=[\n",
        "        {\"role\": \"developer\", \"content\": system_prompt},\n",
        "        {\"role\": \"user\", \"content\": \"Alice and Bob are going to a science fair on Friday.\"},\n",
        "    ]\n",
        ")\n",
        "\n",
        "# Response is string not json\n",
        "print(response.output_text)\n",
        "dictionary = json.loads(response.output_text)\n",
        "print(dictionary[\"name\"])\n",
        "# print(dictionary.name) # Will not work because dictionary is not an object"
      ],
      "metadata": {
        "id": "2IPLSF30K--S",
        "colab": {
          "base_uri": "https://localhost:8080/"
        },
        "outputId": "4497908e-1b93-4c90-f280-2c01749120ac"
      },
      "execution_count": null,
      "outputs": [
        {
          "output_type": "stream",
          "name": "stdout",
          "text": [
            "{\"name\": \"Science Fair\", \"date\": \"Friday\", \"participants\": [\"Alice\", \"Bob\"]}\n",
            "Science Fair\n"
          ]
        }
      ]
    },
    {
      "cell_type": "markdown",
      "source": [
        "A similar example, except for the user input."
      ],
      "metadata": {
        "id": "MfKM-UYGSu_x"
      }
    },
    {
      "cell_type": "code",
      "source": [
        "system_prompt = \"\"\"\n",
        "Extract the event information from the users message and provide output in\n",
        "exact json format as follows -\n",
        "{\"name\": \"Dinner\", \"date\": \"Monday\", \"participants\": [\"Michael\", \"David\"]}\n",
        "\"\"\"\n",
        "response = openai.responses.create(\n",
        "    model=MODEL,\n",
        "    input=[\n",
        "        {\"role\": \"developer\", \"content\": system_prompt},\n",
        "        {\"role\": \"user\", \"content\": \"Leonardo, Ivan and Alex will be joining Taylor for dinner on Tuesday night.\"},\n",
        "    ]\n",
        ")\n",
        "print(response.output_text)\n",
        "dictionary = json.loads(response.output_text)\n",
        "print(dictionary[\"name\"])"
      ],
      "metadata": {
        "colab": {
          "base_uri": "https://localhost:8080/"
        },
        "id": "sejIL04-WVCe",
        "outputId": "4e3271ab-7395-400d-8b0a-c4a8a72e5de6"
      },
      "execution_count": null,
      "outputs": [
        {
          "output_type": "stream",
          "name": "stdout",
          "text": [
            "{\"name\": \"Dinner\", \"date\": \"Tuesday\", \"participants\": [\"Taylor\", \"Leonardo\", \"Ivan\", \"Alex\"]}\n",
            "Dinner\n"
          ]
        }
      ]
    }
  ]
}